import crypto from 'crypto';
import { promisify } from 'util';
const generateKeyPair = promisify(crypto.generateKeyPair);

// 安全生成密钥对
export const initKeyPair = async () => {
  try {
    return await generateKeyPair('rsa', {
      modulusLength: 2048,
      publicKeyEncoding: { type: 'spki', format: 'pem' },
      privateKeyEncoding: {
        type: 'pkcs8',
        format: 'pem',
        cipher: 'aes-256-cbc',
        passphrase: process.env.RSA_PASSPHRASE || 'default-strong-password'
      }
    });
  } catch (err) {
    console.error('密钥生成错误:', err);
    throw err;
  }
};

// 测试密钥生成
(async () => {
  try {
    const { publicKey, privateKey } = await initKeyPair();
    console.log('公钥:', publicKey);
    console.log('私钥:', privateKey);
  } catch (err) {
    console.error('初始化失败:', err.message);
  }
})();